import React, {Component} from 'react';
import {Breadcrumb, message, Form, Input, Button, Select, Switch, Modal, Table, Space} from "antd";
import {NavLink} from "react-router-dom";
import {connect} from "react-redux";

const {Option} = Select;

@connect(state => ({userInfo: state.userInfo}))
class Admin extends Component {
    state = {
        changepassword: {},
        dialogpw: false, //密码框
        loading: false,
        dialogFormVisibleadd: false, //添加弹框
        form: {},
        user: {
            username: "",
            password: "",
            password1: ""
        },
        pagelistquery: {
            total: 0,
            page: 1,
            pagesize: 10,
            user: "",
            state: ""
        },
        tableData: [] //列表信息
    }
    registered = (values) => {
        const userReg = /^[1-9a-zA-Z]{1}[0-9a-zA-Z]{5,9}$/; //6-10位字母数字
        const pwdReg = /^[1-9a-zA-Z]\w{5,17}$/; //6-18位字母数字下划线，数字字母开头
        if (!userReg.test(values.username)) {
            message.error("账号为6-10位字母数字字母,不能以0开头");
            return;
        }
        if (!pwdReg.test(values.password)) {
            message.error("密码为6-18位字母数字或下划线");
            return;
        }
        if (values.password !== values.password1) {
            message.error("两次密码不相等");
            return;
        }
        values = {...this.state.user, ...values};
        this.setState({user: values});
        this.$axios.post("/admin/registered", values)
            .then(result => {
                let data = result.data;
                if (data.state.type !== "SUCCESS") {
                    if (data.state.type === "ERROR_PARAMS_EXIST") {
                        message.error("账户名重复");
                    } else {
                        message.error("账号添加失败失败");
                    }
                    return;
                }
                message.success("账号添加成功");
                this.setState({dialogFormVisibleadd: false})
                this.getAdminList();
                this.refs.addUser.resetFields()
            })
            .catch(e => {
                message.error(e);
            });
    }
    changeState = async (checked, text, row) => {
        if (checked) {
            row[text] = "1";
        } else row[text] = "0"
        let result = await this.$axios.post("/admin/changeadminstate", row);
        if (result.data.state.type === "SUCCESS") {
            message.success("更改授权成功");
        }
    }
    getAdminList = async (values) => {
        this.setState({loading: true});
        values = {...this.state.pagelistquery, ...values};
        this.setState({pagelistquery: values});
        let result = await this.$axios.post("/admin/getadminlist", values);
        if (result.data.state.type === "SUCCESS") {
            let pagelistquery = this.state.pagelistquery;
            pagelistquery.total = result.data.count;
            this.setState({tableData: result.data.data, pagelistquery: pagelistquery});
            this.setState({loading: false});
        }
    }
    changePw = (row) => {
        this.setState({dialogpw: true, changepassword: row});
    }
    getPassword = (values) => {
        let changepassword = this.state.changepassword;
        if (values.newpassword) {
            changepassword.newpassword = values.newpassword;
            this.setState({changepassword: changepassword});
            this.changePassword();
        } else message.error("密码不能为空")
    }
    //修改密码
    changePassword = async () => {
        let changepassword = this.state.changepassword;
        changepassword.type = "adminadmin";
        this.setState({changepassword: changepassword});
        let result = await this.$axios.post("/admin/changepassword", this.state.changepassword);
        if (result.data.state.type === "SUCCESS") {
            message.success("修改成功");
            this.setState({dialogpw: false, changepassword: {}});
            this.refs.editPW.resetFields()
        }
    }
    handleSizeChange = (current, size) => {
        let pagelistquery = this.state.pagelistquery
        pagelistquery.pagesize = size;
        this.setState({pagelistquery: pagelistquery});
        this.getAdminList();
    }
    handleCurrentChange = (page, pagesize) => {
        let pagelistquery = this.state.pagelistquery;
        pagelistquery.page = page;
        pagelistquery.pagesize = pagesize;
        this.setState({pagelistquery: pagelistquery});
        this.getAdminList();
    }
    deleteAdmin = async (row) => {
        let data = {
            user_id: row.user_id,
            usertype: "admin"
        };
        let result = await this.$axios.post("/admin/deleteuser", data);
        if (result.data.state.type === "SUCCESS") {
            message.success("删除成功");
            this.getAdminList();
        }
    }

    componentDidMount() {
        this.getAdminList();
    }

    render() {
        const {
            changepassword, dialogFormVisibleadd, dialogpw, loading, tableData
        } = this.state;
        tableData.map((item, index) => {
            return item.key = index;
        })
        const columns = [
            {
                title: "账号",
                dataIndex: "username"
            },
            {
                title: "昵称",
                dataIndex: "nickname"
            },
            {
                title: "审核中心",
                dataIndex: "issh",
                render: (text, record) => (
                    <Switch defaultChecked={text === "1" ? true : false}
                            onChange={(checked) => this.changeState(checked, "issh", record)}
                            disabled={record.username === "admin"}
                    ></Switch>
                )
            },
            {
                title: "用户管理",
                dataIndex: "isyh",
                render: (text, record) => (
                    <Switch defaultChecked={text === "1" ? true : false}
                            onChange={(checked) => this.changeState(checked, "isyh", record)}
                            disabled={record.username === "admin"}
                    ></Switch>
                )
            },
            {
                title: "网站管理中心",
                dataIndex: "isgl",
                render: (text, record) => (
                    <Switch defaultChecked={text === "1" ? true : false}
                            onChange={(checked) => this.changeState(checked, "isgl", record)}
                            disabled={record.username === "admin"}
                    ></Switch>
                )
            },
            {
                title: "反馈中心",
                dataIndex: "isfk",
                render: (text, record) => (
                    <Switch defaultChecked={text === "1" ? true : false}
                            onChange={(checked) => this.changeState(checked, "isfk", record)}
                            disabled={record.username === "admin"}
                    ></Switch>
                )
            },
            {
                title: "账号状态",
                dataIndex: "user_state",
                render: (text, record) => (
                    <Switch defaultChecked={text === "1" ? true : false}
                            onChange={(checked) => this.changeState(checked, "user_state", record)}
                            disabled={record.username === "admin"}
                    ></Switch>
                )
            },
            {
                title: "操作",
                dataIndex: "user_id",
                render: (text, record) => (
                    <Space size="small">
                        <Button type="text" style={{color: "#409EFF"}} size={"small"} onClick={() => {
                            this.deleteAdmin(record)
                        }}
                                disabled={record.username === "admin"}
                        >删除</Button>
                        <Button type="text" style={{color: "#409EFF"}} size={"small"} onClick={() => {
                            this.changePw(record)
                        }}
                        >修改密码</Button>
                    </Space>
                )
            },
        ]
        return (
            <div>
                <div className="top">
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <NavLink to='/'>首页</NavLink>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            用户管理
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            管理员用户管理
                        </Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div className="main">
                    <div>
                        <Form onFinish={this.getAdminList} layout={"inline"}>
                            <Form.Item name="user" initialValue=""
                                       style={{width: '15%', margin: "15px 10px 22px 0"}}>
                                <Input placeholder="账号查找"></Input>
                            </Form.Item>
                            <Form.Item name="state" initialValue=""
                                       style={{width: '20%', margin: "15px 10px 22px 0"}}>
                                <Select placeholder="状态">
                                    <Option value="">全部</Option>
                                    <Option value="1">启用</Option>
                                    <Option value="0">停用</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item style={{margin: "15px 10px 22px 0"}}>
                                <Button type="primary" htmlType="submit">查询</Button>
                            </Form.Item>
                            <Form.Item style={{margin: "15px 10px 22px 0"}}>
                                <Button type="primary"
                                        onClick={() => this.setState({dialogFormVisibleadd: true})}>添加账号</Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <Table dataSource={tableData}
                           columns={columns} bordered
                           loading={loading}
                           pagination={{
                               total: this.state.pagelistquery.total,
                               showSizeChanger: true,
                               showQuickJumper: true,
                               onChange: this.handleCurrentChange,
                               onShowSizeChange: this.handleSizeChange,
                               showTotal: total => `共 ${total} 条`,
                               position: ["bottomLeft"]
                           }}
                    ></Table>
                </div>
                {/*添加新的账号*/}
                <Modal visible={dialogFormVisibleadd} title="添加新的账号"
                       onCancel={() => this.setState({dialogFormVisibleadd: false})}
                       footer={false}
                >
                    <Form onFinish={this.registered} labelCol={{span: 4}} ref={"addUser"}>
                        <Form.Item name="username" label="账号：" initialValue="">
                            <Input/>
                        </Form.Item>
                        <Form.Item name="password" initialValue="" label="密码:">
                            <Input.Password/>
                        </Form.Item>
                        <Form.Item name="password1" initialValue="" label="确认密码:">
                            <Input.Password/>
                        </Form.Item>
                        <Form.Item>
                            <Space style={{float: "right"}}>
                                <Button onClick={() => this.setState({dialogFormVisibleadd: false})}>
                                    取消
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    确定
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>
                {/*密码框*/}
                <Modal visible={dialogpw} title="输入新的密码"
                       onCancel={() => this.setState({dialogpw: false})}
                       footer={false}
                >
                    <Form onFinish={this.getPassword} labelCol={{span: 4}} ref={"editPW"}>
                        <Form.Item label="账号：">
                            {changepassword.username}
                        </Form.Item>
                        <Form.Item name="newpassword" initialValue="" label="新密码:">
                            <Input/>
                        </Form.Item>
                        <Form.Item>
                            <Space style={{float: "right"}}>
                                <Button onClick={() => this.setState({dialogpw: false})}>
                                    取消
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    确定
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Admin;
